package com.javasm.springmybatis.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author：longjinyi
 * @Version：1.0
 * @Date：2021/12/29-15:49
 * @Since:jdk1.8
 * @Description:
 */
public class MailTest {
    public static void main(String[] args) throws Exception {
        sendMail("cd262233@163.com","ROEENVEGGFXUPWLA","2622117233@qq.com","努力敲代码的程序猿，不当码农");
    }

    private static void sendMail(String from,String password,String to,String content) throws MessagingException {
        //创建一个配置文件并保存
        Properties properties = new Properties();

        //设置发送邮件的服务器
        //发件邮箱：改动1
        properties.setProperty("mail.host","smtp.163.com");

        //邮件发送协议
        properties.setProperty("mail.transport.protocol","smtp");

        //设置需要验证用户名和密码
        properties.setProperty("mail.smtp.auth","true");

        //这里SMTP启用SSL安全连接
        properties.put("mail.smtp.ssl.enable", "true");

        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {

            //发件邮箱：改动2
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //括号里面的参数
                //第一个参数：发送邮件的网易邮箱的账号
                //第二个参数：网易邮箱的授权码
                //授权码填错报：535 Error: authentication failed 异常
                return new PasswordAuthentication(from,password);
            }
        });

        //开启debug模式
        session.setDebug(true);

        //获取连接对象
        Transport transport = session.getTransport();

        //连接服务器(连接发送邮件的服务器)
        //发件邮箱：改动3(账号和授权码)
        transport.connect("smtp.163.com",from,password);

        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);

        //邮件发送人(网易邮箱)
        //发件邮箱：改动4(发件人邮箱账号)
        mimeMessage.setFrom(new InternetAddress(from));

        //邮件接收人(qq邮箱)
        //接收邮箱：改动5(收件人邮箱账号)
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(to));

        //邮件标题
        mimeMessage.setSubject("入职通知书");

        //邮件内容
        mimeMessage.setContent(content,"text/html;charset=UTF-8");

        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

        //关闭连接
        transport.close();
    }
}
